/**
 * <pre>
 * Copyright:		Copyright(C) 2005-2006, Jdkcn.com
 * Filename:		MD5Util.java
 * Date:			2006-5-19 11:44:38
 * Author:			<a href="mailto:rory.cn@gmail.com">somebody</a>
 * Description:		MD5加密工具类
 *
 * </pre>
 **/
package sdfsjdf.sfsd.sdf.sdfs;

import java.security.MessageDigest;

import javax.crypto.Mac;
import javax.crypto.SecretKey;

/**
 * @author <a href="mailto:rory.cn@gmail.com">somebody</a>
 * @since 2006-5-19 11:44:38
 * @version $Id$
 */
public class MD5Util {

	private MD5Util() {
	}

	public static String encryptPassword(String password) {
		if (password == null) {
			password = "";
		}
		return digest(password);
	}

	private static String digest(String myinfo) {
		try {
			MessageDigest alga = MessageDigest.getInstance("MD5");
			alga.update(myinfo.getBytes());
			byte[] digesta = alga.digest();
			return byte2hex(digesta);
		} catch (Exception ex) {
			return myinfo;
		}
	}

	public static String hmac(String info, String key) {
		try {
			SecretKey sk = new javax.crypto.spec.SecretKeySpec(key.getBytes(),
					"HmacMD5");
			Mac mac = Mac.getInstance("HmacMD5");
			mac.init(sk);
			byte[] digesta = mac.doFinal(info.getBytes());
			return byte2hex(digesta);
		} catch (Exception e) {
			//e.printStackTrace();
			return info;
		}
	}

	private static String byte2hex(byte[] b) { // 二行制转字符串
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
			if (n < b.length - 1) {
				hs = hs + "";
			}
		}
		return hs.toLowerCase();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("---");
		System.out.println(MD5Util.hmac("df4411fb9b106604559eadb35442be92",
				"feloo"));
	}

}
